package com.bw.contorller;

import com.bw.entity.HuoDai;
import com.bw.entity.User;
import com.bw.service.HuodaiService;
import org.hibernate.validator.constraints.EAN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class HuodaiContorller {
    @Autowired
    HuodaiService huodaiService;
    @RequestMapping("toindex")
    public String toIndex(){
        return "index";
    }
    //列表展示
    @RequestMapping("list")
    public String toList(HuoDai huoDai, Model model, HttpSession httpSession){
        //从域对象获取用户
        User user = (User) httpSession.getAttribute("user");
        Integer status2 = user.getStatus2();
        huoDai.setStatus2(status2);
        String uname = user.getUname();
        huoDai.setUname(uname);
        List<HuoDai> list=huodaiService.list(huoDai);
        model.addAttribute("s",huoDai);
        model.addAttribute("list",list);
        return "list";
    }

    //去添加
    @RequestMapping("toadd")
    public String toAdd(HttpSession session,Model model){
        User user = (User) session.getAttribute("user");
        model.addAttribute("u",user);
        return "add";
    }
    //获取普通用户
    @ResponseBody
    @RequestMapping("selectUser")
    public List<User> selectUser(){
        List<User> list=huodaiService.selectUser();
        return list;
    }

    //获取文件
    @ResponseBody
    @RequestMapping("getFile")
    public String getFile(MultipartFile file) throws IOException {
        String path="d:/pic/";
        String originalFilename = file.getOriginalFilename();
        String s = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        File file1 = new File(path, s);
        file.transferTo(file1);
        return "/pic/"+s;
    }

    //修改状态
    @ResponseBody
    @RequestMapping("deleteByid")
    public int deleteByid(Integer ids){
        int i=huodaiService.deleteByid(ids);
        return i;
    }

    //执行添加
    @RequestMapping("add")
    public String Add(HuoDai huoDai){
        int i=huodaiService.add(huoDai);
        if(i>0){
            return "redirect:toindex";
        }
        return "add";
    }

}
